import { interpreter } from "@/api/request";
import { getConversationMessage } from "@/api/zixun";
import type { ChatItemProps } from "@/components/Chat/chat.vue";
import debounce from "@/utils/debounce";
import Lnkyeah from "@/utils/lnkyeah";
import PlayVoice from "@/utils/playVoice";
import { computed, ref } from "vue";

export default function useChat() {
  const source: Record<number, Array<ChatItemProps>> = {};
  const chats = ref<Array<ChatItemProps>>([]);
  const chating = ref<Boolean>(false);
  const pagination = ref<
    Record<
      number,
      {
        page: number;
        per_page: number;
        total: number;
      }
    >
  >({});

  function stop(index: number) {
    if (!PlayVoice.context.paused) {
      PlayVoice.instance.stop();
    }
    if (chats.value[index]) {
      chats.value[index].playing = 0;
    }
  }
  async function playing(message: string, index: number) {
    if (chats.value) {
      const target = chats.value[index];
      if (target.voiceUrl) {
        chats.value[index].playing = 2;
        await PlayVoice.instance.play(target.voiceUrl!);
        // 播放完成
        stop(index);
      } else {
        chats.value[index].playing = 1;
        Lnkyeah.instance.once("tts", async (e: any) => {
          const activeIndex = getActiveRobot.value;
          if (activeIndex > -1) {
            chats.value[activeIndex].playing = 0;
            chats.value[activeIndex].voiceUrl = e.url;
            // if (chats.value[activeIndex].playing === 2) {
            //   await PlayVoice.instance.play(e.url);
            //   stop(activeIndex);
            // }
          }
        });
        Lnkyeah.instance.getVoice(message);
      }
    }
  }

  const getActiveRobot = computed(() => {
    return chats.value.findIndex(
      item => item.playing !== undefined && item.playing !== 0
    );
  });

  const getConversationHistory = async (id: number, forceUpdate = false) => {
    if (!pagination.value[id] || forceUpdate) {
      pagination.value[id] = {
        per_page: 10,
        page: 1,
        total: 0
      };
    }
    const { per_page, page, total } = pagination.value[id];
    if (page > Math.ceil(total / per_page) && total > 0) {
      return;
    }
    const [err, res] = await interpreter(
      getConversationMessage(id, { per_page, page })
    );
    if (!err) {
      pagination.value[id].page += 1;
      pagination.value[id].total = res.total;
      if (source[id]) {
        source[id] = res.data.concat(source[id]);
      } else {
        source[id] = res.data;
      }
      chats.value = source[id];
    }
  };

  const onGetAudio = debounce(async (message: string, index: number) => {
    const playingIndex = getActiveRobot.value;
    if (playingIndex === index) {
      stop(playingIndex);
      return;
    }
    if (playingIndex > -1) {
      stop(playingIndex);
    }
    await playing(message, index);
  });

  const stopAll = () => {
    const playingIndex = getActiveRobot.value;
    stop(playingIndex);
  };

  return {
    source,
    chats,
    chating,
    stop,
    stopAll,
    getActiveRobot,
    getConversationHistory,
    onGetAudio
  };
}
